package com.gzx.plugin.tjzy.modular.call.predict.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.gzx.plugin.tjzy.modular.call.predict.bo.GzxPredictCallAddBo;
import com.gzx.plugin.tjzy.modular.call.predict.bo.GzxPredictCallExcelBo;
import com.gzx.plugin.tjzy.modular.call.predict.entity.GzxPredictCall;
import com.gzx.plugin.tjzy.modular.call.predict.entity.GzxPredictCallDetail;
import com.gzx.plugin.tjzy.modular.call.predict.enums.GzxCallBatchStatusEnum;
import com.gzx.plugin.tjzy.modular.call.predict.mapper.GzxPredictCallDetailMapper;
import com.gzx.plugin.tjzy.modular.call.predict.mapper.GzxPredictCallMapper;
import com.gzx.plugin.tjzy.modular.call.predict.service.GzxPredictCallDbService;
import com.gzx.plugin.tjzy.modular.call.predict.vo.GzxPredictAllVo;
import com.gzx.plugin.tjzy.modular.call.predict.vo.GzxPredictCallDetailVo;
import com.gzx.plugin.tjzy.modular.call.predict.vo.GzxPredictCallVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.consts.IntConstant;
import vip.xiaonuo.common.util.*;

import java.util.List;
import java.util.stream.Collectors;

import static org.apache.commons.lang.StringEscapeUtils.escapeSql;

/**
 * @author zjt
 * @description
 * @date 2025/6/9 16:35
 */
@Service
@RequiredArgsConstructor
@DS("tjzy-async")
public class GzxPredictCallDbServiceImpl implements GzxPredictCallDbService {

    private final GzxPredictCallMapper predictCallMapper;

    private final GzxPredictCallDetailMapper predictCallDetailMapper;

    //获取线路信息
    @DS("tjzy-async")
    @Override
    public List<GzxPredictAllVo> getCallerInfo(String currentMonth) {
        return predictCallMapper.getCallerInfo(currentMonth);
    }

    /**
     * 查询单条预测外呼数据
     *
     * @param lambdaQueryWrapper
     * @return
     */
    @Override
    public GzxPredictCall selectOne(LambdaQueryWrapper<GzxPredictCall> lambdaQueryWrapper) {
        return predictCallMapper.selectOne(lambdaQueryWrapper);
    }

    /**
     * 查询预测外呼集合
     *
     * @param lambdaQueryWrapper
     * @return
     */
    @Override
    public List<GzxPredictCall> selectList(LambdaQueryWrapper<GzxPredictCall> lambdaQueryWrapper) {
        return predictCallMapper.selectList(lambdaQueryWrapper);
    }

    /**
     * 分页查询预测外呼主表
     *
     * @param page
     * @param lambdaQueryWrapper
     * @return
     */
    @Override
    public Page<GzxPredictCallVo> selectVoPage(Page page, LambdaQueryWrapper<GzxPredictCall> lambdaQueryWrapper) {
        return predictCallMapper.selectVoPage(new Page<>(page.getCurrent(), page.getSize()), lambdaQueryWrapper);
    }

    /**
     * 保存预测外呼主表
     *
     * @param predictCallAddBo
     * @param userJson
     * @param totalCount
     */
    @Override
    public void saveBatch(GzxPredictCallAddBo predictCallAddBo, JSONObject userJson, Integer totalCount) {
        //保存批次表
        GzxPredictCall predictCall = MapstructUtils.convert(predictCallAddBo, GzxPredictCall.class);
        predictCall.setId(IdUtil.getSnowflakeNextId());
        predictCall.setTotalCount(totalCount);
        predictCall.setCaller(predictCallAddBo.getCallNumber());
        predictCall.setBatchStatus(GzxCallBatchStatusEnum.CHECKING.getCode());
        predictCall.setCreateUser(userJson.getStr("id"));
        predictCall.setCreateDept(userJson.getStr("orgId"));
        predictCall.setTenantId(userJson.getStr("tenantId"));
        predictCallMapper.insert(predictCall);
    }

    /**
     * 修改预测外呼主表数据
     *
     * @param lambdaUpdateWrapper
     */
    @Override
    public void update(LambdaUpdateWrapper<GzxPredictCall> lambdaUpdateWrapper) {
        predictCallMapper.update(lambdaUpdateWrapper);
    }

    /**
     * 根据ID修改预测外呼主表数据
     *
     * @param predictCall
     */
    @Override
    public void updateById(GzxPredictCall predictCall) {
        predictCallMapper.updateById(predictCall);
    }

    /**
     * 删除
     *
     * @param lambdaUpdateWrapper
     */
    @Override
    public void delete(LambdaUpdateWrapper<GzxPredictCall> lambdaUpdateWrapper) {
        predictCallMapper.delete(lambdaUpdateWrapper);
    }

    /**
     * 分页查询预测外呼明细表
     *
     * @param page
     * @param lambdaQueryWrapper
     * @return
     */
    @Override
    public Page<GzxPredictCallDetailVo> selectDetailVoPage(Page page, LambdaQueryWrapper<GzxPredictCallDetail> lambdaQueryWrapper) {
        return predictCallDetailMapper.selectVoPage(new Page<>(page.getCurrent(), page.getSize()), lambdaQueryWrapper);
    }

    /**
     * 查询预测外呼明细
     *
     * @param lambdaQueryWrapper
     * @return
     */
    @Override
    public List<GzxPredictCallDetail> selectDetailList(LambdaQueryWrapper<GzxPredictCallDetail> lambdaQueryWrapper) {
        return predictCallDetailMapper.selectList(lambdaQueryWrapper);
    }

    /**
     * 根据Detail查询ID
     *
     * @param id
     * @return
     */
    @Override
    public GzxPredictCallDetailVo selectDetailVoById(Long id) {
        return predictCallDetailMapper.selectVoById(id);
    }

    /**
     * 批量保存预测外呼明细
     *
     * @param predictCallAddBo
     * @param predictCallExcelBoList
     * @param user
     */
    @Override
    public void saveDetail(GzxPredictCallAddBo predictCallAddBo, List<GzxPredictCallExcelBo> predictCallExcelBoList, JSONObject user) {
        List<GzxPredictCallDetail> predictCallDetailList = MapstructUtils.convert(predictCallExcelBoList, GzxPredictCallDetail.class);
        for (GzxPredictCallDetail predictCallDetail : predictCallDetailList) {
            predictCallDetail.setBatchNumber(predictCallAddBo.getBatchNumber());
            predictCallDetail.setCaller(predictCallAddBo.getCallNumber());
            if (StringUtils.isBlank(predictCallDetail.getCustomerInfo()) || !predictCallDetail.getCustomerInfo().startsWith("姓名")) {
                predictCallDetail.setCustomerInfo("姓名：" + predictCallDetail.getLiaisonName() + "，电话：" + CommonSensitiveUtil.sensitivePhone(predictCallAddBo.getIsPhoneAes() == 1 ? CommonCryptogramUtil.doSm1AesDecrypt(predictCallDetail.getLiaisonPhone()) : predictCallDetail.getLiaisonPhone()) + (StringUtils.isNotBlank(predictCallDetail.getCustomerInfo()) ? "，信息：" + predictCallDetail.getCustomerInfo() : ""));
            } else {
                predictCallDetail.setCustomerInfo(predictCallDetail.getCustomerInfo());
            }
            predictCallDetail.setCreateUser(user.getStr("id"));
            predictCallDetail.setCreateDept(user.getLong("orgId"));
            predictCallDetail.setTenantId(user.getStr("tenantId"));
        }
        String currentDate = CommonDateUtil.getCurrentTimeStr();
        List<List<GzxPredictCallDetail>> batchList = Lists.partition(predictCallDetailList, IntConstant.VALUE_1000);
        for (List<GzxPredictCallDetail> batch : batchList) {
            String sql = batch.stream()
                    .map(s -> String.format("(%s,'%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s')",
                            escapeSql(IdUtil.getSnowflakeNextIdStr()),
                            escapeSql(s.getBatchNumber()),
                            escapeSql(s.getCaller()),
                            escapeSql(s.getLiaisonName()),
                            escapeSql(CommonCryptogramUtil.doSm1AesEncrypt(s.getLiaisonPhone())),
                            escapeSql(s.getCustomerInfo()),
                            escapeSql(s.getPartnerBusinessId()),
                            escapeSql(String.valueOf(s.getCaseId())),
                            escapeSql(s.getTenantId()),
                            escapeSql(String.valueOf(s.getCreateDept())),
                            escapeSql(String.valueOf(s.getCreateUser())),
                            escapeSql(currentDate)))
                    .collect(Collectors.joining(", "));
            predictCallDetailMapper.insertBatchByValSql(sql.replace("'null'", "null"));
            CommonSleepUtil.sleep(IntConstant.VALUE_100);
        }
    }

    /**
     * 修改预测外呼明细数据
     *
     * @param lambdaUpdateWrapper
     */
    @Override
    public void updateDetail(LambdaUpdateWrapper<GzxPredictCallDetail> lambdaUpdateWrapper) {
        predictCallDetailMapper.update(lambdaUpdateWrapper);
    }

    /**
     * 删除预测外呼明细
     *
     * @param lambdaUpdateWrapper
     */
    @Override
    public void deleteDetail(LambdaUpdateWrapper<GzxPredictCallDetail> lambdaUpdateWrapper) {
        predictCallDetailMapper.delete(lambdaUpdateWrapper);
    }

    /**
     * 修改预测外呼状态和数量
     *
     * @param sortedTaskIdList
     */
    @Override
    public void modifyBatchStatusAndCount(List<String> sortedTaskIdList) {
        predictCallMapper.modifyBatchStatusAndCount(sortedTaskIdList);
    }
}
